package com.wash.shoes.controller.pc;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.R;
import com.wash.shoes.common.enums.OrderStatusEnum;
import com.wash.shoes.entity.AccessoriesPo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.QualityInspectionPo;
import com.wash.shoes.entity.ShoePo;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.request.QualityInspectByWashCodeRequest;
import com.wash.shoes.request.QualityInspectQueryRequest;
import com.wash.shoes.resp.QualityInspectRecordResp;
import com.wash.shoes.service.IAccessoriesService;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.service.ShoeService;
import com.wash.shoes.service.impl.QualityInspectionServiceImpl;
import com.wash.shoes.util.AdminUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@Slf4j
@Api(tags = {"PC-质检接口"})
@RequiredArgsConstructor
@RequestMapping({"/pc/qualityInspection", "/dev-api/qualityInspection", "qualityInspection"})
public class QualityInspectionController {

    private final OrderService orderService;

    private final ShoeService shoeService;

    private final IAccessoriesService accessoriesService;

    private final QualityInspectionServiceImpl qualityInspectionService;

    @ApiOperation(value = "根据订单号获取质检列表", response = QualityInspectRecordResp.class)
    @GetMapping("/getQualityListByOrderId")
    public R<List<QualityInspectRecordResp>> getQualityInspectionListByOrderId(@Valid QualityInspectQueryRequest qualityInspectQueryRequest) {
//        OrderPo orderPo = orderService.getById(qualityInspectQueryRequest.getOrderId());
        //查询这个订单下的所有鞋子
        List<ShoePo> shoes = shoeService.getByOrderId(qualityInspectQueryRequest.getOrderId());

        List<QualityInspectRecordResp> data = shoes.stream().map(shoePo -> {
                    QualityInspectRecordResp resp = QualityInspectRecordResp.builder().build();
                    resp.setId(shoePo.getId());
                    resp.setItemType(shoePo.getItemType());
                    resp.setWashCode(shoePo.getWashCode());
                    resp.setImages(Arrays.asList(shoePo.getPicture().split(",")));
                    //获取这个订单 这件物品的配饰
                    List<AccessoriesPo> accessoriesPos = accessoriesService.list(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, shoePo.getOrderId()).eq(AccessoriesPo::getBizId, shoePo.getId()));
                    if (CollectionUtil.isNotEmpty(accessoriesPos)) {
                        //配饰列表
                        resp.setAccessories(accessoriesPos.stream().map(accessoriesPo -> QualityInspectRecordResp.Accessories.builder().name(accessoriesPo.getType()).washCode(accessoriesPo.getWashCode()).status(accessoriesPo.getStatus()).build()).collect(Collectors.toList()));
                    }
                    //设置货架号
                    resp.setSrgCode(shoePo.getSrgCode());
                    resp.setRemarks(Lists.newArrayList(shoePo.getRemark()));
                    return resp;
                }
        ).collect(Collectors.toList());
        //构件返回记录
        return R.ok(data);
    }

    /**
     * 验证订单是否允许质检
     *
     * @param orderId
     * @return
     */
    private boolean valid(String orderId) {
        cn.hutool.core.lang.Assert.notNull(orderId, "验证是否允许质检orderid不能为空.");
        //订单物品的数量
        OrderPo orderPo = orderService.getById(orderId);
        //判断订单状态只有待质检的时候才能质检
        if (OrderStatusEnum.WAIT_FOR_QUALITY.getStatus().equals(orderPo.getStatus())) {
            return true;
        }
        throw new WashException("订单状态不是待质检,orderId:" + orderId);
    }

    /**
     * 根据水洗码获取质检记录
     *
     * @param bizId 鞋子id或者配饰id
     * @return
     */
    private QualityInspectionPo getQualityInspectionPo(String bizId) {
        QualityInspectionPo qualityInspectionPo = qualityInspectionService.getOne(new LambdaQueryWrapper<QualityInspectionPo>().eq(QualityInspectionPo::getBizId, bizId));
        if (qualityInspectionPo != null) {
            return qualityInspectionPo;
        }
        return null;
    }

    @ApiOperation(value = "根据水洗码质检物品")
    @PostMapping("/qualityInspectByWashCode")
    @Transactional
    public R<?> qualityInspectByWashCode(@RequestBody @Valid QualityInspectByWashCodeRequest inspectByWashCodeRequest) {
        ShoePo shoePo = shoeService.shoeDetailByWashCode(inspectByWashCodeRequest.getWashCode());
        String orderId = null;
        //先找物品再找配件的
        if (shoePo == null) {
            AccessoriesPo accessoriesPo = accessoriesService.getOne(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getWashCode, inspectByWashCodeRequest.getWashCode()));
            Assert.notNull(accessoriesPo, "未找到此水洗码");
            accessoriesPo.setStatus(1);//设置成已质检
            accessoriesService.updateById(accessoriesPo);
            orderId = accessoriesPo.getOrderId();
            //判断订单状态只有待质检的时候才能质检
            valid(orderId);
            QualityInspectionPo qualityInspectionPo = getQualityInspectionPo(accessoriesPo.getId());
            if (Objects.isNull(qualityInspectionPo)) {
                qualityInspectionPo = new QualityInspectionPo();
            }
            //生成一条质检记录
            qualityInspectionPo.setType(accessoriesPo.getType());
            qualityInspectionPo.setWashCode(accessoriesPo.getWashCode());
            qualityInspectionPo.setBizId(accessoriesPo.getId());
            qualityInspectionPo.setOrderId(accessoriesPo.getOrderId());
            qualityInspectionPo.setStatus("1");
            qualityInspectionPo.setExtendInfo(accessoriesPo.getExtendInfo());
            qualityInspectionPo.setRemark(accessoriesPo.getRemark());
            qualityInspectionPo.setUrl(accessoriesPo.getUrl());
            qualityInspectionPo.setCreateTime(accessoriesPo.getCreateTime());
            qualityInspectionPo.setUpdateTime(accessoriesPo.getUpdateTime());
//            qualityInspectionPo.setCreateBy(AdminUserUtil.getUserId());
            qualityInspectionPo.setUpdateBy(AdminUserUtil.getLoginUserName());
            qualityInspectionService.saveOrUpdate(qualityInspectionPo);
        } else {
            orderId = shoePo.getOrderId();
            //判断订单状态只有待质检的时候才能质检
            valid(shoePo.getOrderId());
            shoePo.setQualityInspectionTime(LocalDateTime.now());
            shoePo.setQualityInspector(AdminUserUtil.getLoginUserName());
            shoePo.setQualityInspectorStatus("1");//设置成已质检

            QualityInspectionPo qualityInspectionPo = getQualityInspectionPo(shoePo.getId());
            if (Objects.isNull(qualityInspectionPo)) {
                qualityInspectionPo = new QualityInspectionPo();
            }

            //生成一条质检记录
//            QualityInspectionPo qualityInspectionPo = new QualityInspectionPo();
            qualityInspectionPo.setType("物品");//设置成物品
            qualityInspectionPo.setWashCode(shoePo.getWashCode());
            qualityInspectionPo.setBizId(shoePo.getId());
            qualityInspectionPo.setOrderId(shoePo.getOrderId());
            qualityInspectionPo.setStatus("1");
            qualityInspectionPo.setExtendInfo(shoePo.getExtendInfo());
            qualityInspectionPo.setRemark(shoePo.getRemark());
            qualityInspectionPo.setUrl(shoePo.getPicture());
            qualityInspectionPo.setCreateTime(new Date());
            qualityInspectionPo.setUpdateTime(new Date());
//            qualityInspectionPo.setCreateBy(AdminUserUtil.getUserId());
            qualityInspectionPo.setUpdateBy(AdminUserUtil.getLoginUserName());
            //保存质检记录
            qualityInspectionService.saveOrUpdate(qualityInspectionPo);

            shoeService.updateById(shoePo);
        }

        //订单物品的数量
        OrderPo orderPo = orderService.getById(orderId);


        //查询这个订单已质检的数量
        long qualityInspectionNum =/* qualityInspectionService.count(new LambdaQueryWrapper<QualityInspectionPo>().eq(QualityInspectionPo::getOrderId, orderId).eq(QualityInspectionPo::getStatus, "1"))*/qualityInspectionService.getBaseMapper().queryCountByOrderId(orderId);
        //查询这个订单已质检的配件数量/物品配饰
        long accessoriesNum = iAccessoriesService.count(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, orderId)/*.eq(AccessoriesPo::getStatus, 1)*/);
        long shoeNum = shoeService.count(new LambdaQueryWrapper<ShoePo>().eq(ShoePo::getOrderId, orderId)/*.eq(ShoePo::getStatus, 1)*/);
        //订单的鞋子数量+配件数量=质检数量
        if ((shoeNum + accessoriesNum) == qualityInspectionNum) {
            //TODO 全部质检完成
            orderPo.setStatus(OrderStatusEnum.PENDING_OUTBOUND.getStatus());
            orderPo.setQualityInspTime(LocalDateTime.now());//设置成质检完成时间
            orderService.updateById(orderPo);
        }
        //TODO  这里质检完成需要把订单改成待出库
        //查询这个订单下的所有鞋子
//        List<ShoePo> shoes=shoeService.getByOrderId()

        return R.ok();
    }

    @Autowired
    private IAccessoriesService iAccessoriesService;
}